<template>
	<view>
		<free-nav-bar :title="detail.name" :fixed="false" :showback="true" @openExtend="openExtends" showright>
			<free-icon-button slot="right" @click="naviset">&#xe6fd;</free-icon-button>

		</free-nav-bar>

		<scroll-view scroll-y class="bg-light position-fixed left-0 right-0 px-3"
			style="bottom: 105rpx;z-index: 9999999;" :style="chatBodyBottom" @click="clickscroll"
			:scroll-into-view="scrollinto">
			<view v-for="(item,index) in list" :id="'chatItem_'+index">

				<free-chat-item :item="item" @long="longchat" ref="chatItem" :index="index"
					:pretime="index>0 ? list[index-1].create_time:0" @preview="previewimage">
				</free-chat-item>

			</view>

			<!-- 	<view class="flex align-start justify-end position-relative">

				<view class=" p-2 rounded mr-3 bg-chat-item" style="max-width: 500rpx;">
					<text class="font-md "></text>
				</view>
				<text class="iconfont text-chat-item font-md position-absolute"
					style="right: 80rpx;top:20rpx">&#xe640;</text>
				<free-avater size="70"
					src="https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1">
				</free-avater>
			</view>
 -->
		</scroll-view>

		<view class="position-fixed left-0 right-0  border-top flex align-center"
			style="background: #f7f7f6;height: 105rpx;z-index: 9999999;" :style="'bottom:'+KeyboardHeight+'px'">
			<free-icon-button @click="changemode('audio')" v-if="mode == 'text'">&#xe606;</free-icon-button>
			<free-icon-button @click="changemode('text')" v-if="mode == 'audio'">&#xe607;</free-icon-button>

			<view class="flex-1">
				<view v-if="mode == 'audio'" class="rounded flex justify-center align-center"
					:class="isrecord ? 'bg-hover-light':'bg-white'" style="height: 80rpx;">
					<text class="font font-lg" @touchstart="voiceTouchStart" @touchend="voiceTouchEnd"
						@touchcancel="voiceTouchCancel" @touchmove="voiceTouchMove">{{isrecord ? '松开结束' :'按住说话'}}</text>
				</view>
				<textarea fixed class="border bg-white font-md rounded p-1" style="height: 75rpx;width: 100%;"
					v-model="text" v-if="mode == 'text'" placeholder="请输入" :adjust-position="false"
					@focus="onfocustext" />

			</view>
			<free-icon-button @click="openemoction">&#xe605;</free-icon-button>
			<free-icon-button @click="openaction" v-if="text==''">&#xe603;</free-icon-button>
			<view v-if="text!==''" class="main-bg-color rounded mr-3 px-2 py-1" @click="send('text')">
				<text class="font text-white">发送</text>


			</view>
		</view>
		<free-popup ref="action" fixedBottom :mask="false">
			<view class="border-top border-light-secondary" style="height: 580rpx;">
				<swiper :indicator-dots="true" style="height: 510rpx;">
					<swiper-item class="row">
						<view class="col-3 h225 flex flex-column align-center justify-center" @click="uploadimage">
							<image src="../../static/images/extends/pic.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">相册</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center" @click="uploadVideo">
							<image src="../../static/images/extends/video.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">拍摄</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center">
							<image src="../../static/images/extends/phone.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">视频通话</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center">
							<image src="../../static/images/extends/path.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">位置</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center">
							<image src="../../static/images/extends/hongbao.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">红包</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center">
							<image src="../../static/images/extends/audio.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">语音输入</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center">
							<image src="../../static/images/extends/shoucan.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">我的收藏</text>
						</view>
						<view class="col-3 h225 flex flex-column align-center justify-center">
							<image src="../../static/images/extends/man.png" mode="widthFix"
								style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-light-muted">名片</text>
						</view>
					</swiper-item>

				</swiper>

			</view>


		</free-popup>
		<free-popup ref="emoction" fixedBottom :mask="false">

			<view class="border-top border-light-secondary " style="height: 580rpx;overflow: auto;">
				<view class="flex flex-wrap">
					<view class="col-3 h225 flex flex-column align-center justify-center flex-wrap"
						@click="sendem(item.icon)" v-for="item in emoclist">
						<image :src="item.icon" mode="" style="width: 100rpx;height: 100rpx;"></image>
						<view class="font text-light-muted">
							{{item.name}}

						</view>
					</view>

				</view>

			</view>
		</free-popup>

		<free-popup ref="extend" maskColor :bodyWidth="240" :bodyHeight="getMenusHeight" :tabbarHeight="105">
			<view class="flex flex-column free-animation" :style="getMenusStyle">

				<view class="flex-1 flex align-center" @click="clickevemt(item.event)" hover-class="bg-light"
					v-for="item in getMenus">
					<text class="font-md pl-2">{{item.name}}</text>
				</view>

			</view>
		</free-popup>
		<view v-if="isrecord" class="position-fixed top-0 right-0 left-0 flex justify-center align-center"
			style="    z-index: 99999999; bottom: 105rpx;position: fixed;">
			<view style="width: 360rpx;height: 360rpx;background: rgba(0,0,0,0.5);"
				class="rounded flex flex-column align-center justify-center">
				<image src="/static/images/audio/play.gif" style="width: 150rpx;height: 150rpx;" mode=""></image>
				<text class="font text-white mt-3">{{unrecord ? '松开手指，取消发送' :'手指上滑，取消发送'}} </text>
			</view>

		</view>
	</view>
</template>
<style>
	.h225 {
		height: 225rpx;
	}
</style>
<script>
	// #ifdef APP-PLUS-NVUE
	const dom = weex.requireModule('dom')
	// #endif
	const RECORD = uni.getRecorderManager();
	import {
		mapState,
		mapMutations
	} from "vuex"
	import freeIconButton from "@/components/free-ui/free-icon-button.vue"
	import freeNavBar from "@/components/free-ui/free-nav-bar.vue"
	import freeAvater from "@/components/free-ui/free-avater.vue"
	import freePopup from "@/components/free-ui/free-popup.vue"
	import auth from "@/common/mixin/auth.js"
	import freeChatItem from "@/components/free-ui/free-chat-item.vue"
	export default {
		mixins: [auth],
		components: {
			freeNavBar,
			freeAvater,
			freePopup,
			freeChatItem,
			freeIconButton,
		},
		onLoad(e) {
			console.log(e, "eeeef");
			if (!e.params) {
				uni.showToast({
					title: "非法参数",
					icon: "none"
				})
				uni.navigateBack({
					delta: 1
				})
			}
			console.log(JSON.parse(decodeURIComponent((e.params))), "JSON.parse(decodeURIComponent((e.params)))")
			this.detail = JSON.parse(decodeURIComponent((e.params)))
			this.detail.chat_type = e.type

			this.chat.createchatobject(this.detail);
			this.list = this.chat.getChatDetail()
			setTimeout(()=>{
		this.pageToBottom()
				
			},100)
			console.log(this.list, "list");
			uni.$on("onMessage", res => {
				console.log(res, "res")
				console.log(this.detail, "detail")
				if (res.from_id === this.detail.id && res.chat_type === this.detail.chat_type) {
					this.list.push(res)
					setTimeout(()=>{
					this.pageToBottom()
							
						},100)
				}
			})
		},
		mounted() {
			console.log(this.title, "title");
			// #ifdef APP-PLUS-NVUE
			this.statusBarHeight = plus.navigator.getStatusbarHeight();
			console.log(this.statusBarHeight);
			// #endif
			this.navBarHeight = this.statusBarHeight + uni.upx2px(90)
			uni.onKeyboardHeightChange(res => {
				console.log(res, "res");
				if (this.mode !== 'action') {
					this.KeyboardHeight = res.height

				}
				if (this.KeyboardHeight > 0) {
					this.pageToBottom()

				}
			})
			// //监听录音开始
			// RECORD.onStart(e=>{
			// 	this.recordtime=0
			// 	this.recordTimer=setInterval(()=>{
			// 		this.recordtime++;
			// 	},1000)
			// })
			// //监听录音结束
			// RECORD.onStop(e=>{
			// 	if(this.recordTimer){
			// 		clearInterval(this.recordTimer)
			// 	}
			// 	console.log(e,"onstop");
			// 	if(!this.unrecord){
			// 		let time = (new Date()).getTime();
			// 		let obj = {
			// 			avater: "https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1",
			// 			user_id: 1,
			// 			nickname: "亚刻",
			// 			type: "audio", //image,audio,video
			// 			options: {
			// 				time: this.recordtime
			// 			},
			// 			create_time: time,
			// 			data: e.tempFilePath,
			// 			isremove: false,

			// 		}

			// 		this.list.push(obj)

			// 		this.pageToBottom()
			// 	}

			// })
			this.regSendVoiceEvent((url) => {
				if (!this.unrecord) {
					let time = (new Date()).getTime();
					let obj = {
						avater: "https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1",
						user_id: 1,
						nickname: "亚刻",
						type: "audio", //image,audio,video
						options: {
							time: this.recordtime
						},
						create_time: time,
						data: url,
						isremove: false,

					}

					this.list.push(obj)

					this.pageToBottom()
				}
			})
		},
		data() {
			return {
				isrecord: false,
				// recordTimer:null,
				emoclist: [{
						name: "沮丧",
						icon: require("../../static/images/emoticon/5497/0.gif"),
						event: "uploadImage"
					},
					{
						name: "嫌弃",
						icon: require("../../static/images/emoticon/5497/1.gif"),
						event: "uploadImage"
					},
					{
						name: "瑟瑟发抖",
						icon: require("../../static/images/emoticon/5497/2.gif"),
						event: "uploadImage"
					},
					{
						name: "干杯",
						icon: require("../../static/images/emoticon/5497/3.gif"),
						event: "uploadImage"
					},
					{
						name: "亲亲",
						icon: require("../../static/images/emoticon/5497/4.gif"),
						event: "uploadImage"
					},
					{
						name: "摸鱼",
						icon: require("../../static/images/emoticon/5497/5.gif"),
						event: "uploadImage"
					},
					{
						name: "鬼脸",
						icon: require("../../static/images/emoticon/5497/6.gif"),
						event: "uploadImage"
					},
					{
						name: "干杯",
						icon: require("../../static/images/emoticon/5497/7.gif"),
						event: "uploadImage"
					},
					{
						name: "机枪",
						icon: require("../../static/images/emoticon/5497/8.gif"),
						event: "uploadImage"
					},
					{
						name: "吐",
						icon: require("../../static/images/emoticon/5497/9.gif"),
						event: "uploadImage"
					},
					{
						name: "嘿嘿",
						icon: require("../../static/images/emoticon/5497/0.gif"),
						event: "uploadImage"
					},
				],
				scrollinto: "",
				statusBarHeight: 0,
				mode: "text",
				text: "",
				KeyboardHeight: 0,
				propIndex: -1,
				menu: [{
						name: "复制",
						event: ""
					},
					{
						name: "发送给朋友",
						event: ""
					},
					{
						name: "收藏",
						event: ""
					}, {
						name: "提醒",
						event: ""
					}, {
						name: "翻译",
						event: ""
					}, {
						name: "删除",
						event: ""
					},
					{
						name: "撤回",
						event: "remove"
					},
					{
						name: "多选",
						event: ""
					},
				],
				navBarHeight: 0,
				recordStartY: 0,
				unrecord: false,
				detail: {},
				//录音时长
				// recordtime:0,
				list: []
			}
		},
		watch: {
			mode(newValue, oldValue) {
				console.log(newValue, oldValue, "new");
				if (newValue !== 'action' && newValue !== 'emoticon') {
					this.KeyboardHeight = 0
					this.$refs.action.hidden();
				}

			}
		},
		computed: {
			...mapState({
				RECORD: state => state.audio.RECORD,
				recordtime: state => state.audio.recordtime,
				chat: state => state.user.chat
			}),
			getMenusHeight() {
				let H = 100;
				return this.menu.length * H
			},

			getMenusStyle() {

				return `width:240rpx;height: ${this.getMenusHeight}rpx;`
			},
			isdoself() {
				let id = 1;
				console.log(this.propIndex, "propIndex");
				let user_id = this.propIndex > -1 ? this.list[this.propIndex].user_id : 0;
				console.log(user_id, "user_id");
				return user_id == id;
			},
			getMenus() {
				return this.menu.filter(v => {
					
					//不是本人
					if (v.name === '撤回' && !this.isdoself) {
						console.log("1");
						return false
					} else {
						console.log("2");
						return true
					}
				})
			},
			chatBodyBottom() {
				return `bottom:${uni.upx2px(105)+this.KeyboardHeight}px;top:${this.navBarHeight}px`
			},
			imageList() {
				let arr = [];
				this.list.forEach(el => {
					if (el.type === 'image' || el.type === 'emoticon') {
						arr.push(el.data)
					}
				})
				return arr;
			}

		},
		destroyed() {
			this.chat.destroychatobject()
			uni.$off("onMessage", () => {

			})
		},
		methods: {
			...mapMutations(['regSendVoiceEvent']),
			uploadVideo() {
				uni.chooseVideo({
					maxDuration: 10,
					success: (res) => {
						console.log(res, "res");
						var time = (new Date()).getTime();
						var obj = {
							avater: "https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1",
							user_id: 1,
							nickname: "亚刻",
							type: "video", //image,audio,video
							create_time: time,
							data: res.tempFilePath,
							isremove: false,

						}

						this.list.push(obj)

						this.pageToBottom()
					}
				})
			},
			voiceTouchStart(e) {
				console.log(e, "ee");
				this.recordStartY = e.changedTouches[0].screenY
				this.isrecord = true
				this.unrecord = false
				this.RECORD.start({
					format: "mp3"
				})
			},
			voiceTouchEnd() {
				this.isrecord = false
				// this.unrecord=false
				this.RECORD.stop()
			},

			voiceTouchCancel() {
				this.isrecord = false
				this.unrecord = true
				this.RECORD.stop()
			},
			voiceTouchMove(e) {

				// this.isrecord = false
				let Y = Math.abs(e.changedTouches[0].screenY - this.recordStartY);
				console.log(Y, "Y");
				this.unrecord = (Y >= 50)

			},
			naviset() {
				console.log(12333);
				uni.navigateTo({
					url: "/pages/chat/chatset?params="+JSON.stringify({
						id:this.detail.id,
						chat_type:this.detail.chat_type
						
					})
				})
			},
			changemode(text) {
				console.log(text);
				this.mode = text
				console.log(this.mode);
			},
			previewimage(e) {
				console.log(e, "e");
				uni.previewImage({
					current: e,
					urls: this.imageList
				})
			},
			uploadimage() {
				uni.chooseImage({
					count: 9,
					success: (res => {
						console.log(res, "res")
						res.tempFilePaths.forEach(el => {
							this.sendimagefromxc(el);
						})
					})
				})
			},
			openemoction() {
				this.mode = "emoticon";
				this.$refs.action.hidden();
				this.KeyboardHeight = 0;

				this.$refs.emoction.show();
				uni.hideKeyboard()
				this.KeyboardHeight = uni.upx2px(580)
			},
			openaction() {
				this.mode = "action"
				console.log(this.mode);
				this.$refs.emoction.hidden();
				this.$refs.action.show();
				uni.hideKeyboard()
				this.KeyboardHeight = uni.upx2px(580)
			},
			focustext() {
				console.log("1233");
				this.$refs.action.hidden();
				this.KeyboardHeight = 0;

			},
			onfocustext() {
				this.mode = "text"
				this.$refs.action.hidden();
				this.KeyboardHeight = 0;
			},
			//相册
			sendimagefromxc(item) {
				var time = (new Date()).getTime();
				var obj = {
					avater: "https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1",
					user_id: 1,
					nickname: "亚刻",
					type: "image", //image,audio,video
					create_time: time,
					data: item,
					isremove: false,

				}

				this.list.push(obj)

				this.pageToBottom()

			},
			send(type) {
				console.log(type, "type")
				let message = this.chat.formatSendData({
					type: type,
					data: this.text
				})
				let index = this.list.length
				this.list.push(message)
				this.text = ""
				this.chat.send(message).then(res => {
					console.log(res, res.id, "send")
					this.list[index].id = res.id;
					this.list[index].sendStatus = 'success'
					setTimeout(()=>{
					this.pageToBottom()
							
						},100)
				}).catch(err => {
					console.log(err, "errsend")
					this.list[index].sendStatus = 'fail'
				})
				// var time = (new Date()).getTime();
				// var obj = {
				// 	avater: "https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1",
				// 	user_id: 1,
				// 	nickname: "亚刻",
				// 	type: "text", //image,audio,video
				// 	create_time: time,
				// 	data: this.text,
				// 	isremove: false,

				// }
				// if (type == 'text') {
				// 	this.list.push(obj)
				// 	this.text = ""
				// 	this.pageToBottom()
				// }
			},
			sendem(data) {
				var time = (new Date()).getTime();
				var obj = {
					avater: "https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1",
					user_id: 1,
					nickname: "亚刻",
					type: "emoticon", //image,audio,video
					create_time: time,
					data: data,
					isremove: false,

				}

				this.list.push(obj)

				setTimeout(() => {
					this.pageToBottom()

				}, 300)


			},
			pageToBottom() {


				// #ifdef APP-PLUS-NVUE
				let chatItem = this.$refs.chatItem;
				let lastIndex = chatItem.length > 0 ? chatItem.length - 1 : 0;
				if (chatItem[lastIndex]) {
					dom.scrollToElement(chatItem[lastIndex], {})
				}
				// #endif

				console.log("1233345");
				if(this.$refs.chatItem){
				let chatItem = this.$refs.chatItem;
				let lastIndex = chatItem.length > 0 ? chatItem.length - 1 : 0;
				this.scrollinto = 'chatItem_' + lastIndex
									
				}

				// let last=chatItem[chatItem.length-1];

			},
			longchat(e) {
				console.log(e, "e");
				this.propIndex = e.index
				this.$refs.extend.show(e.x, e.y)
			},
			clickevemt(itemevent) {
				console.log(itemevent, "itemevent");
				if (itemevent == 'remove') {
					this.list[this.propIndex].isremove = true
					this.$refs.extend.hidden();
				}

			},
			clickscroll() {
				console.log("click");
				this.$refs.action.hidden();
				this.KeyboardHeight = 0
			}


		}
	}
</script>

<style>

</style>
